package com.du.fileload.controller;

import com.du.fileload.framework.config.DFileCache;
import com.du.fileload.framework.config.DFileLoad;
import com.du.fileload.framework.config.JWTConfig;
import com.du.fileload.framework.entity.RequestFileDataBody;
import com.du.fileload.framework.entity.SysUserAbstract;
import com.du.fileload.framework.utils.Code;
import com.du.fileload.framework.utils.FileUploadUtils;
import com.du.fileload.framework.utils.FileUtils;
import com.du.fileload.framework.utils.JwtUtil;
import com.du.plugin.common.entity.JResult;
import com.du.plugin.common.tool.HandleException;
import com.du.plugin.common.tool.MD5;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author fx
 */
@RestController
public class CommonController{
	private static final Logger log = LoggerFactory.getLogger(CommonController.class);

	@Autowired
	private DFileCache fileCache;
	@Autowired
	private DFileLoad fileLoad;

	/**
	 * 授权获取token
	 */
	@PostMapping("/common/auth")
	public JResult auth(@RequestBody SysUserAbstract sysUser) throws Exception {
		try {
			if(sysUser.getUsername()==null||sysUser.getPassword()==null){
				return JResult.newError("用户名/密码不能为空");
			}
			String userCredential=String.format("%s:%s",sysUser.getUsername(),sysUser.getPassword());
			//验证码用户名是否一致
			boolean authResult=DFileLoad.getInstance().getAuthUsers().contains(userCredential);
			if(!authResult){
				return JResult.newError("认证失败");
			}
			Map<String, Object> claims=new HashMap<>();
			claims.put(JWTConfig.getInstance().getMainKey(), MD5.toMd5(String.format("%s%s",userCredential,sysUser.getPassword()),2));
			String jwtStr= JwtUtil.generate(claims);
			return JResult.newSuccess(jwtStr);
		} catch (Exception e) {
			return JResult.newError(e.getMessage());
		}
	}


	/**
	 * 通用图片压缩
	 */

	@GetMapping("/common/compress")
	public JResult compressFile(String fileUrl, Integer cl) throws Exception {
		try {
			String filePath=FileUploadUtils.getAbsolPathFileName(fileUrl);
			if(!new File(filePath).exists()){
				return JResult.newError("资源不存在");
			}
			String fileName = FileUploadUtils.compressResourceApi(fileUrl,cl);
			return JResult.newInstance(true).settClass(fileName);
		} catch (Exception e) {
			return JResult.newError(e.getMessage());
		}
	}

	/**
	 * 通用上传请求
	 */
	@PostMapping("/common/upload")
	public JResult uploadFile(MultipartFile file, Integer cl) throws Exception {
		try {
			RequestFileDataBody fileDataBody=new RequestFileDataBody();
			fileDataBody.setFile(file);
			fileDataBody.setCl(cl);
			// 上传并返回新文件名称
			String fileName = FileUploadUtils.upload(fileDataBody);
			return JResult.newInstance(true).settClass(fileName);
		} catch (Exception e) {
			return JResult.newError(e.getMessage());
		}
	}

	/**
	 * 通用下载请求
	 *
	 * @param fileName
	 *            文件名称
	 * @param delete
	 *            是否删除
	 */
	@GetMapping("/common/download")
	public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
		try {
			String filePath= FileUploadUtils.getAbsolPathFileName(fileName);
			File file=new File(filePath);
			if(!file.exists()){
				response.getWriter().write("文件不存在："+fileName);
				return;
			}
			String fullName = Code.toUtf8String(file.getName());// 用来解决下载后文件名中文乱码
			response.setHeader("content-type", "application/octet-stream");
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + fullName);
			try {
				FileUtils.writeBytes(filePath, response.getOutputStream());
			} catch (IOException e) {
				log.error("下载文件失败", e);
			}
		} catch (Exception e) {
			HandleException.addEx(e);
			log.error("下载文件失败", e);
		}
	}

	@GetMapping("/common/delete")
	public JResult delete(String filePath) {
		return JResult.newError("");
	}
}
